package com.lin.filegraph.utils.parser.astvisitor;

import com.lin.filegraph.utils.parser.node.JFileNode;
import com.lin.filegraph.utils.parser.node.JImportNode;
import com.lin.filegraph.utils.parser.node.JProjectNode;
import com.lin.filegraph.utils.parser.simpleast.SimpleASTHelper;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ImportDeclaration;

/**
 * @description:
 * @author: linhuaixu
 * @time: 2023/5/18 14:08
 */

public class ImportVisitor extends ASTVisitor {

    private String filePath;
    private CompilationUnit compilationUnit;
    private JFileNode fileNode;
    private JProjectNode root;

    public ImportVisitor(JFileNode fileNode, JProjectNode root) {
        // TODO Auto-generated constructor stub
        this.fileNode = fileNode;
        this.fileNode = fileNode;
        this.filePath = fileNode.getFilePath();
        this.compilationUnit = fileNode.getCompilationUnit();
        this.root = root;
    }

    @Override
    public boolean visit(ImportDeclaration node) {

        String strFullImportName = node.getName().getFullyQualifiedName();
        String strPkgName = strFullImportName;
        if (!node.isOnDemand()) {
            if(strFullImportName.contains(".")) {
                strPkgName = strFullImportName.substring(0, strFullImportName.lastIndexOf("."));
            } else {
                strPkgName = "default package";
            }

        }

        JImportNode importNode = null;
        if (SimpleASTHelper.isPkgExist(strPkgName, root)) {
            importNode = new JImportNode(filePath, node, strPkgName, strFullImportName, true);
        } else {
            importNode = new JImportNode(filePath, node, strPkgName, strFullImportName, false);
        }
        fileNode.addChildNode(importNode);
        return false;
    }

    public void traverse() {
        compilationUnit.accept(this);
    }
}

